﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;

namespace SmartDesktop
{
    public class UIHelper
    {
        public static ToolStripButton CreateToolStripButton(Image imageMenuLeft, string tooltipText)
        {
            ToolStripButton tlsButton = new ToolStripButton();
            tlsButton.AutoSize = false;
            tlsButton.Width = 102; tlsButton.Height = 90;
            tlsButton.BackgroundImage = imageMenuLeft; tlsButton.BackgroundImageLayout = ImageLayout.Stretch;
            tlsButton.ToolTipText = tooltipText;
            return tlsButton;
        }

        public static void DataGridViewCellFormatting(System.Windows.Forms.DataGridView grid, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
        {
            if ((grid.Rows[e.RowIndex].DataBoundItem != null) && (grid.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
            {
                e.Value = BindProperty(grid.Rows[e.RowIndex].DataBoundItem, grid.Columns[e.ColumnIndex].DataPropertyName);
            }
        }

        private static string BindProperty(object property, string propertyName)
        {
            string retValue = "";

            if (propertyName.Contains("."))
            {
                PropertyInfo[] properties;
                string leftPropertyName;

                leftPropertyName = propertyName.Substring(0, propertyName.IndexOf("."));
                properties = property.GetType().GetProperties();

                foreach (PropertyInfo propertyInfo in properties)
                {
                    if (propertyInfo.Name == leftPropertyName)
                    {
                        retValue = BindProperty(propertyInfo.GetValue(property, null), propertyName.Substring(propertyName.IndexOf(".") + 1));
                        break;
                    }
                }
            }
            else
            {
                Type propertyType;
                PropertyInfo propertyInfo;

                propertyType = property.GetType();
                propertyInfo = propertyType.GetProperty(propertyName);
                retValue = propertyInfo.GetValue(property, null).ToString();
            }

            return retValue;
        }

    }
}
